package com.yogee.topseller.activity.login.view.impl;

import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.AppManager;
import com.yogee.core.utils.NetUtil;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.MainActivity1;
import com.yogee.topseller.activity.login.model.bean.InterestLabelBean;
import com.yogee.topseller.activity.my.MaintainLablesActivity;
import com.yogee.topseller.adapter.InterestLabelAdapter;
import com.yogee.topseller.adapter.InterestLabelRegisterAdapter;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.http.Config;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.LogUtils;
import com.yogee.topseller.view.DividerItemDecoration;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class RegisterLabelActivity extends HttpActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.rv_interest_label)
    RecyclerView rvInterestLabel;
    @BindView(R.id.tv_commit_interest_label)
    TextView tvCommitInterestLabel;

    InterestLabelRegisterAdapter mAdapter;
    ArrayList<InterestLabelBean> mLabelDatas;

    private String isMain;
    private String userid;

    @Override
    protected void initView() {
        mLabelDatas = new ArrayList<>();
        rvInterestLabel.setLayoutManager(new LinearLayoutManager(this));
        rvInterestLabel.setAdapter(mAdapter = new InterestLabelRegisterAdapter(this));
        rvInterestLabel.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
        rvInterestLabel.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        userid = AppUtil.getUserId(this);
        labelList(userid);
    }
 
    @Override
    protected int getLayoutId() {
        return R.layout.activity_register_label;
    }

    @OnClick({R.id.back, R.id.tv_commit_interest_label})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (AppUtil.isFastDoubleClick(500)) {
                    return;
                }
//                finish();
                AppManager.finishAllActivity();
                startActivity(new Intent(RegisterLabelActivity.this, MainActivity1.class));
                finish();
                break;
            case R.id.tv_commit_interest_label:
                String selectLabel = "";
                List<InterestLabelBean.ListBean.LabelListBean> bean = mAdapter.getmSelectBean();//获得标签集合
                for (int i = 0; i < bean.size(); i++) {
                    selectLabel += "," + bean.get(i).getId();
                }
                try{
                    selectLabel = selectLabel.substring(1, selectLabel.length());
                }catch (Exception e){
                }

                if (!selectLabel.equals("")) {
                    setlabels(selectLabel, userid);
                } else {
                    ToastUtils.showToast(this, "请选择您感兴趣的标签");
                }
                break;
        }
    }

    private void labelList(String userid) {
        HttpManager.getInstance().labelList(userid).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<InterestLabelBean>() {
            @Override
            public void onNext(InterestLabelBean o) {
                mAdapter.addData(o.getList());
            }
        }, this));
    }

    private void setlabels(String labels, String userId) {
        if(pd!=null)
            pd.show();
        HttpManager.getInstance().setlabels(labels, userId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                    if (o.getResult().equals("1")) {
                        AppManager.finishAllActivity();
                        startActivity(new Intent(RegisterLabelActivity.this, MainActivity1.class));
                        finish();
                }
            }
        }, this));
    }


    private void setlabels1(String labels, String userId) {
        if (!NetUtil.isNetworkAvailable()) {
            ToastUtils.showToast(RegisterLabelActivity.this, "网络中断了，请重新链接网络。");
            return;
        }
        if(pd!=null)
            pd.show();

        //组装调取银行卡验证api的数据
        JSONObject object = new JSONObject();
        try {
            object.put("userId", userId);
            object.put("labels", labels);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //网络调取api
//        OkHttpClient okHttpClient = new OkHttpClient();

        OkHttpClient okHttpClient =
                new OkHttpClient.Builder()
                        .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                        .writeTimeout(60,TimeUnit.SECONDS)//设置写的超时时间
                        .connectTimeout(60,TimeUnit.SECONDS)//设置连接超时时间
                        .build();
        Request.Builder builder = new Request.Builder();
        RequestBody requestBody = RequestBody
                .create(MediaType.parse("text/plain;chaset=utf-8"), object.toString());
        Request request = builder.post(requestBody)
                .url(Config.BASE_URL+"setLabels")
//                .addHeader("Authorization", "APPCODE " + appCode)
                .addHeader("Content-Type", "application/json; charset=UTF-8")
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        //失败处理
//                        if (progressBar.isShowing()){
//                            progressBar.dismiss();
//                        }
                        if(pd!=null)
                            pd.dismiss();
                        ToastUtils.showToast(RegisterLabelActivity.this, "保存失败");
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        //成功处理
//                        if (progressBar.isShowing()){
//                            progressBar.dismiss();
//                        }
                        pd.dismiss();
                        //组装json来回显银行卡号
                        try {
                            Gson gson = new Gson();
                            String result = response.body().string().replace("\n","");
                            LogUtils.e("success",result);
                            JSONObject jsonObject = new JSONObject(result);
                            ResultBean o = gson.fromJson(jsonObject.getString("data"),ResultBean.class);
                            if (o.getResult().equals("1")) {
                                ToastUtils.showToast(RegisterLabelActivity.this,"保存成功");
                                AppManager.finishAllActivity();
                                startActivity(new Intent(RegisterLabelActivity.this, MainActivity1.class));
                                finish();
                            }
                        } catch (Exception e) {
                            ToastUtils.showToast(RegisterLabelActivity.this, "保存失败");
                            LogUtils.e("fail",e.toString());
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}